package com.dhcc.sds.base.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.dhcc.cdc.sys.dao.CdcProductMapper;
import com.dhcc.cdc.sys.dao.DictionaryMapper;
import com.dhcc.cdc.sys.dao.DictypeMapper;
import com.dhcc.cdc.sys.entity.CdcProductEntity;
import com.dhcc.cdc.sys.entity.DictionaryEntity;
import com.dhcc.cdc.sys.entity.DictypeEntity;
import com.dhcc.core.config.properties.SysProperties;
import com.dhcc.core.framework.base.service.impl.BaseServiceImpl;
import com.dhcc.core.framework.result.node.ZTreeNode;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.sds.base.dao.SdsQcentityMapper;
import com.dhcc.sds.base.dao.SdsQcfitemDicMapper;
import com.dhcc.sds.base.dao.SdsQcfitemMatchRuleMapper;
import com.dhcc.sds.base.dao.SdsQcformItemMapper;
import com.dhcc.sds.base.entity.*;
import com.dhcc.sds.base.service.ISdsCommonService;
import com.dhcc.sds.base.service.ISdsQcformItemService;
import com.dhcc.sds.standard.dao.SdsStandDicMapper;
import com.dhcc.sds.standard.dao.SdsStandSourceFieldMapper;
import com.dhcc.sds.standard.dao.SdsStandSourceMapper;
import com.dhcc.sds.standard.entity.SdsStandDicEntity;
import com.dhcc.sds.standard.entity.SdsStandSourceEntity;
import com.dhcc.sds.standard.entity.SdsStandSourceFieldEntity;
import com.dhcc.sds.standard.service.ISdsStandSourceService;
import com.dhcc.sds.util.DateUtil;
import io.swagger.models.auth.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.*;
import java.util.*;

/**
 * 表单项目表表数据服务层接口
 *
 * @author sunyingjie
 * @ClassName: SdsQcformItemServiceImpl
 * @Description: TODO
 * @date 2021-03-22 10:10:46
 */
@Service("sdsQcformItemService")
public class SdsQcformItemServiceImpl extends BaseServiceImpl<SdsQcformItemMapper, SdsQcformItemEntity> implements ISdsQcformItemService {

    @Autowired
    private SdsStandSourceFieldMapper sourceFieldMapper;
    @Autowired
    private SdsStandDicMapper sdsStandDicMapper;
    @Autowired
    private SysProperties sysPro;
    @Autowired
    private SdsQcentityMapper sdsQcentityMapper;
    @Autowired
    private ISdsCommonService sdsCommonService;
    @Autowired
    private CdcProductMapper productMapper;
    @Autowired
    private DictypeMapper dictypeMapper;
    @Autowired
    private DictionaryMapper dictionaryMapper;
    @Autowired
    private SdsQcfitemDicMapper sdsQcfitemDicMapper;
    @Autowired
    private SdsQcfitemMatchRuleMapper sdsQcfitemMatchRuleMapper;
    @Autowired
    private SdsStandSourceMapper sourceMapper;
    @Autowired
    private ISdsStandSourceService standSourceService;

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Override
    public List<SdsQcformItemEntity> page(Page<SdsQcformItemEntity> page, Map<String, Object> map) {
        if ("0".equals(map.get("entityId"))) {
            return new ArrayList<>();
        }
        return this.baseMapper.page(page, map);
    }

    @Override
    public List<SdsQcformItemEntity> list(Map<String, Object> map) {
        return this.baseMapper.list(map);
    }

    @Override
    public JSONObject getFormItemMap(Long entityId) {
        JSONObject jsObj = new JSONObject();
        Map<String, Object> params = new HashMap<>();
        params.put("entityId", entityId);
        jsObj.put("", "");
        List<SdsQcformItemEntity> formItemList = this.baseMapper.list(params);
        for (SdsQcformItemEntity fItem : formItemList) {
            jsObj.put(fItem.getBtCode(), fItem.getBtDesc());
        }
        return jsObj;
    }

    @Override
    public SdsQcformItemEntity getInfoById(Long itemId) {
        SdsQcformItemEntity sdsQcformItemEntity = baseMapper.selectById(itemId);
        Map<String, Object> asmtMap = baseMapper.getAsmtByItemId(itemId);
        Long asmtId = null;
        if (CommonUtil.isNotEmpty(asmtMap)) {
            asmtId = Long.valueOf(asmtMap.get("asmtId").toString());
        }
        sdsQcformItemEntity.setAsmtLinkId(asmtId);
        return sdsQcformItemEntity;
    }

    @Override
    public JSONArray getSourceFieldMap(Long sourceId, Long linkStandSubId) {
        JSONArray array = new JSONArray();
        Wrapper<SdsStandSourceFieldEntity> qw = new EntityWrapper<>();
        SdsStandSourceEntity sourceEntityData = new SdsStandSourceEntity();
        SdsStandSourceEntity sourceEntity = sourceMapper.selectById(sourceId);
        if (!StringUtils.isEmpty(sourceEntity)) {
            String sourceDesc = sourceEntity.getSourceDesc();
            if (Objects.equals("非抗菌药物", sourceDesc) || Objects.equals("抗菌药物", sourceDesc) || Objects.equals("处置操作", sourceDesc)) {
                sourceEntityData = standSourceService.getSourceByDesc("患者医嘱信息");
            } else if (Objects.equals("检验生化", sourceDesc) && StringUtils.isEmpty(linkStandSubId)) {
                sourceEntityData = standSourceService.getSourceByDesc("患者送检报告信息");
            } else if (Objects.equals("影像检查", sourceDesc) && StringUtils.isEmpty(linkStandSubId)) {
                sourceEntityData = standSourceService.getSourceByDesc("检查医嘱+诊断结果信息");
            } else if (Objects.equals("检验生化", sourceDesc) && !StringUtils.isEmpty(linkStandSubId)) {
                sourceEntityData = standSourceService.getSourceByDesc("检验结果信息");
            } else if (Objects.equals("影像检查", sourceDesc) && !StringUtils.isEmpty(linkStandSubId)) {
                sourceEntityData = standSourceService.getSourceByDesc("检查项目结果信息");
            } else {
                sourceEntityData = sourceEntity;
            }

            qw.eq("source_id", sourceEntityData.getId());
            List<SdsStandSourceFieldEntity> sdsStandSourceFieldEntities = sourceFieldMapper.selectList(qw);
            for (SdsStandSourceFieldEntity entity : sdsStandSourceFieldEntities) {
                JSONObject obj = new JSONObject();
                obj.put("value", entity.getId().toString());
                obj.put("text", entity.getFieldDesc());
                array.add(obj);
            }
        }
        return array;

        /*Wrapper<SdsStandSourceFieldEntity> qw = new EntityWrapper<>();
        qw.eq("source_id", sourceId);
        List<SdsStandSourceFieldEntity> sdsStandSourceFieldEntities = sourceFieldMapper.selectList(qw);
        JSONArray array = new JSONArray();
        for (SdsStandSourceFieldEntity entity : sdsStandSourceFieldEntities) {
            JSONObject obj = new JSONObject();
            obj.put("value", entity.getId().toString());
            obj.put("text", entity.getFieldDesc());
            array.add(obj);
        }
        return array;*/
    }

    @Override
    public JSONArray getDicMapBySourceId(Long sourceId) {
        List<SdsStandDicEntity> standDicEntitys = sdsStandDicMapper.selectList(new EntityWrapper<SdsStandDicEntity>()
                .eq("source_id", sourceId));
        JSONArray array = new JSONArray();
        for (SdsStandDicEntity entity : standDicEntitys) {
            JSONObject obj = new JSONObject();
            obj.put("value", entity.getId().toString());
            obj.put("text", entity.getName());
            array.add(obj);
        }
        return array;
    }

    @Override
    public String creatFormHtml(Long entityId) {
        // 获取病种信息
        SdsQcentityEntity entity = this.sdsQcentityMapper.selectById(entityId);
        // 拼装表单html字符串
        String htmlStr = this.updateQCHtml(entityId);
        // 生成html文件
        String fileName = this.createHtmlFile(htmlStr, "/view/backend/sds/sdsqcformshow/", entity.getAbbrev() + ".html");
        // 重置表单项目更新标记
        Wrapper<SdsQcformItemEntity> wrapper = new EntityWrapper<>();
        wrapper.eq("entity_id", entityId);
        this.baseMapper.updateForSet("update_flag=0", wrapper);
        return fileName;
    }

    /**
     * 拼装表单模板HTML字符串
     *
     * @param entityId
     * @return
     */
    private String updateQCHtml(Long entityId) {
        //用于存储html字符串
        StringBuilder formHtml = new StringBuilder(); // 表单模板HTML
        StringBuilder navHtml = new StringBuilder();    // 导航部分
        StringBuilder itemHtml = new StringBuilder();   // 项目内容
        StringBuilder btnHtml = new StringBuilder();    // 按钮部分
        formHtml.append("@layout('/backend/common/_containerForHis.html'){\n");
        formHtml.append("<link href='${ctxPath}/static/backend/sds/sdsqcformshow/SDForm.css' rel='stylesheet'>\n");
        formHtml.append("<#FormHiddenArea></#FormHiddenArea>");
        formHtml.append("<div id=\"FormContent\" style=\"width:100%;height:calc(100% - 50px);overflow-y:auto;background-color:white;margin-bottom:50px;\">");
        formHtml.append("<div id=\"SDNotice\" style=\"margin:0 auto;width:80%;\"></div>");
        formHtml.append("<div style=\"margin:0 10px;width:90%;height:100%;\">");
        navHtml.append("<div id='anchor' class='anchor'><ul class='anchor-list'>");
        Map params = new HashMap();
        params.put("entityId", entityId);
        List<Map<String, Object>> itemCats = this.baseMapper.findItemCats(params);
        int cl = itemCats.size();
        for (int ci = 0; ci < cl; ci++) {
            // 项目大类定义
            String catDesc = itemCats.get(ci).get("itemCat").toString();
            String catCode = catDesc.split("[\\s:：]+")[0]; //按空格分割大类，取数组第一个元素作为code
            String[] subCats = itemCats.get(ci).get("subCats").toString().split("#"); //将子类按逗号分隔
            itemHtml.append("<div class=\"itemCat\" id=\"Title" + ci + "\" onclick=\"objScreen.toggle('" + catDesc + "')\"><span style=\"background-color:#027DFF\">&nbsp;&nbsp;</span>&nbsp;&nbsp;" + catDesc + "</div>");
            itemHtml.append("<div title=\"" + catDesc + "\">");
            //导航html
            navHtml.append("<li style='overflow:hidden;white-space:nowrap;'><div class='circle'></div>");
            navHtml.append("<a href='#Title" + ci + "'>" + catDesc.split("（")[0] + "</a>");
            int sl = subCats.length;
            for (int si = 0; si < sl; si++) {
                String subCat = subCats[si];
                if (CommonUtil.isEmpty(subCat)) {
                    continue;
                }
                itemHtml.append("<p title=\"" + subCat + "\" class=\"itemsubCat\">" + subCat + "</p>");
                params.put("btItemCat", catDesc);
                params.put("btItemSubCat", subCat);
                List<SdsQcformItemEntity> items = this.baseMapper.listByCat(params);
                int ml = items.size();
                for (int mi = 0; mi < ml; mi++) {
                    SdsQcformItemEntity item = items.get(mi);
                    Long itemId = item.getId();
                    String itemCd = item.getBtCode();
                    String itemDesc = item.getBtDesc();
                    String itemTypeCd = item.getBtTypeDict().getCode();
                    String itemTriggerExp = item.getTriggerExp();
                    Integer isNeeded = item.getBtIsNeeded();
                    JSONArray dicArr = JSONArray.parseArray(JSON.toJSONString(item.getFitemDics()));
                    String dicJsonStr = getJsonForJS(dicArr.toString());
                    //必填样式
                    String NeedCss = "";
                    if (isNeeded == 1) NeedCss = "<span name=\"isNeeded\" style=\"color:red\">*</span>";
                    //项目行
                    itemHtml.append("<div class=\"itemTR\" id=\"" + itemId + "_Row\" dic='" + dicJsonStr + "'>");
                    //项目描述
                    itemHtml.append("<div style=\"display:inline-block;width:35%;\" title=\""+itemCd+"\" class=\"itemDescTD\">"+NeedCss+itemDesc+"</div>");
                    //项目填报
                    if (itemTypeCd.contains("Group")) {
                        if (itemTypeCd.equals("RadioGroup") && dicArr.size() > 2) {
                            itemTypeCd = "Combo";
                            itemHtml.append("<input placeholder=\"点击选择\" class=\"" + itemTypeCd + "\" type=\"text\" style=\"width:35%;border:0;height:28px;line-height:28px;\" id=\"" + itemId + "\" itemCode=\"" + item.getBtCode() + "\">");
                        } else {
                            itemHtml.append("<div class=\"" + itemTypeCd + "\" style=\"width:35%;border:0;display:inline-block;\" id=\"" + itemId + "\" itemCode=\"" + item.getBtCode() + "\">" + "</div>");
                        }
                    } else if (itemTypeCd.contains("Combo") || itemTypeCd.contains("Date")) {
                        itemHtml.append("<input placeholder=\"点击选择\" class=\"" + itemTypeCd + "\" type=\"text\" style=\"width:35%;border:0;height:28px;line-height:28px;\" id=\"" + itemId + "\" itemCode=\"" + item.getBtCode() + "\">");
                    } else {
                        itemHtml.append("<input placeholder=\"点击输入\" class=\"" + itemTypeCd + "\" type=\"text\" style=\"width:35%;border:0;height:28px;line-height:28px;\" id=\"" + itemId + "\" itemCode=\"" + item.getBtCode() + "\">");
                    }
                    //获取当前项目评分表信息
                    Map asmtMap = this.baseMapper.getAsmtByItemId(itemId);
                    if (CommonUtil.isNotEmpty(asmtMap)) {
                        itemHtml.append("<a title=\"" + asmtMap.get("asmtDesc") + "\" id=\"" + asmtMap.get("asmtId") + "_Score\"" + "href=\"javascript:\" style=\"font-size:12px;margin-left:12px;color:blue;\" class=\"score-table\">评分工具计算</a>");
                    }
                    //增加数据源溯源按钮
                    itemHtml.append("<a id=\"" + itemId + "_Source\" style=\"width: 20px;margin-left:20px;\" class=\"item-source\"></a>");

                    itemHtml.append("<span style=\"margin-left:10px;\" id=\"" + itemId + "_Note\">" + "" + "</span>");
                    itemHtml.append("</div>");
                }
            }
            navHtml.append("</li>");
            itemHtml.append("</div>");
        }
        navHtml.append("</ul>");
        navHtml.append("</div>\n");

        formHtml.append(itemHtml);
        formHtml.append("</div></div>");
        formHtml.append(navHtml);
        //表单按钮
        formHtml.append("<#FormButton></#FormButton>");
        //更多操作
        formHtml.append("<#MoreTips></#MoreTips>\n");
        formHtml.append("<script src='${ctxPath}/static/backend/sds/sdsqcformshow/sdsformgui.js'></script>\n");
        formHtml.append("@}");

        return formHtml.toString();
    }

    public String judgeItemType(String btTypeCode) {
        String inputType = "text";
        switch (btTypeCode) {
            case "DateT":
                inputType = "datetime";
                break;
            case "Date":
                inputType = "date";
                break;
            case "Combo":
                inputType = "combobox";
                break;
            case "CheckGroup":
                inputType = "checkbox";
                break;
            case "RadioGroup":
                inputType = "radio";
                break;
            case "Num":
                inputType = "number";
                break;
            case "Integer":
                inputType = "integer";
                break;
            default:
                break;
        }
        return inputType;
    }

    /**
     * @param htmlStr  html字符串
     * @param filePath 文件生成的目标路径，例如：D:/wordFile/
     * @param fileName 生成的文件名称，例如：test.html
     * @return 文件名
     * @Desc：生成文件
     * @Author：sunyingjie
     * @Date：2019年3月8日 上午8时54分0秒
     */
    @SuppressWarnings("unchecked")
    public String createHtmlFile(String htmlStr, String filePath, String fileName) {
        try {
            //输出文件
            File outFile = new File(sysPro.getSysHome() + filePath + File.separator + fileName);

            //如果输出目标文件夹不存在，则创建
            if (!outFile.getParentFile().exists()) {
                outFile.getParentFile().mkdirs();
            }

            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));
            out.write(htmlStr);
            //关闭流
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileName;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importItem(Long entityId, List<List<Object>> all) {

        // 如果当前病种项目还没有批量无效,先批量无效
        Wrapper<SdsQcformItemEntity> itemWpr = new EntityWrapper<>();
        itemWpr.eq("entity_id", entityId);
        this.baseMapper.updateForSet("bt_is_active = 0", itemWpr);

        for (int i = 1; i < all.size(); i++) {
            List<Object> ls = all.get(i);
            Integer indNo = null;
            if (CommonUtil.isNotEmpty(ls.get(0))) {
                indNo = Integer.valueOf(ls.get(0).toString()); // 排序
            }
            //String verCode = ls.get(1).toString();
            if (StringUtils.isEmpty(ls.get(2))) {
                continue;
            }
            String itemCode = ls.get(2).toString(); // 项目代码
            String itemDesc = ls.get(3).toString(); // 项目描述
            String btItemCat = ls.get(4).toString(); // 大类
            String btItemSubCat = ls.get(5).toString(); // 子类
            String btUpTypeDesc = ls.get(6).toString(); // 上传类型
            //String triggerExp = ls.get(10).toString(); // 前置条件

            String isNeeded = "";
            String checkTime = "";
            String btTips = "";
            String triggerExp = ""; //新增前置条件
            String btResume = ""; // 备注
            try {
                isNeeded = ls.get(7).toString();
                triggerExp = ls.get(11).toString();
                btResume = ls.get(13).toString();
            } catch (Exception e) {
                log.error("导入表单项目时出错：第" + i + "行，" + e);
            }
            Integer btIsNeeded = CommonUtil.equals(isNeeded, "是") ? 1 : 0; // 是否必填
            Integer btIsActive = 1;
            if (isNeeded.equals("作废")) {
                btIsActive = 0;
            }
            String btTypeDesc = ls.get(12).toString(); // 项目类型
            if (btTypeDesc.contains("单选")) {
                btTypeDesc = "单选字典列表";
            }
            if (btTypeDesc.contains("多选")) {
                btTypeDesc = "多选字典列表";
            }

            CdcProductEntity productEntity = new CdcProductEntity();
            productEntity.setCode("SDS");
            productEntity = productMapper.selectOne(productEntity);
            // 通过项目类型描述获取类型id
            Long btUpTypeId = null;
            if (CommonUtil.isNotEmpty(btTypeDesc)) {
                DictypeEntity dicType = new DictypeEntity();
                dicType.setProductId(productEntity.getId());
                dicType.setCode("UpType");
                dicType = dictypeMapper.selectOne(dicType);
                Map<String, Object> map = new HashMap<>();
                map.put("dictypeId", dicType.getId());
                map.put("description", btUpTypeDesc);
                List<DictionaryEntity> dicList = dictionaryMapper.list(map);
                if (dicList.size() != 0) {
                    btUpTypeId = dicList.get(0).getId();
                }
            }
            // 通过项目类型描述获取类型id
            Long btTypeId = null;
            if (CommonUtil.isNotEmpty(btTypeDesc)) {
                DictypeEntity dicType = new DictypeEntity();
                dicType.setProductId(productEntity.getId());
                dicType.setCode("ItemType");
                dicType = dictypeMapper.selectOne(dicType);
                Map<String, Object> map = new HashMap<>();
                map.put("dictypeId", dicType.getId());
                map.put("description", btTypeDesc);
                List<DictionaryEntity> dicList = dictionaryMapper.list(map);
                if (dicList.size() != 0) {
                    btTypeId = dicList.get(0).getId();
                }
            }

            // 获取质控时机ID
            Long checkTiming = null;
            if (CommonUtil.isNotEmpty(checkTime)) {
                DictypeEntity dicType = new DictypeEntity();
                dicType.setCode("ItemTip");
                dicType = dictypeMapper.selectOne(dicType);
                Map<String, Object> map = new HashMap<>();
                map.put("dictypeId", dicType.getId());
                map.put("description", checkTime);
                List<DictionaryEntity> dicList = dictionaryMapper.list(map);
                if (dicList.size() != 0) {
                    checkTiming = dicList.get(0).getId();
                }
            }

            // 判断表单项目是否重复
            SdsQcformItemEntity item = new SdsQcformItemEntity();
            item.setEntityId(entityId);
            item.setBtCode(itemCode);
            item = this.baseMapper.selectOne(item);
            if (item == null) {
                item = new SdsQcformItemEntity();
                item.setEntityId(entityId);
                item.setBtIndNo(indNo);
                item.setBtCode(itemCode);
                item.setBtDesc(itemDesc);
                item.setBtItemCat(btItemCat.trim());
                item.setBtItemSubCat(btItemSubCat.trim());
                item.setBtIsNeeded(btIsNeeded);
                item.setBtIsActive(btIsActive);
                item.setTriggerExp(triggerExp);
                item.setBtUpType(btUpTypeId);
                item.setBtType(btTypeId);
                item.setBtTips(btTips);
                item.setCheckTiming(checkTiming);
                item.setBtResume(btResume);
                item.setUpdateFlag(1);
                item.setTriggerExp(triggerExp);

                item.insert();
            } else {
                item.setBtIndNo(indNo);
                item.setBtDesc(itemDesc);
                item.setBtItemCat(btItemCat.trim());
                item.setBtItemSubCat(btItemSubCat.trim());
                item.setBtIsNeeded(btIsNeeded);
                item.setBtIsActive(btIsActive);
                item.setTriggerExp(triggerExp);
                item.setBtUpType(btUpTypeId);
                item.setBtType(btTypeId);
                item.setBtTips(btTips);
                item.setCheckTiming(checkTiming);
                item.setBtResume(btResume);
                item.setUpdateFlag(1);
                item.setTriggerExp(triggerExp);

                item.updateAllColumnById();
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importDic(Long entityId, List<List<Object>> all) {
        String formItemCode = "";
        Long formItemId = null;
        Integer indNo = 0;
        Date nowDate = new Date();
        for (int i = 1; i < all.size(); i++) {
            List<Object> ls = all.get(i);
            String sdTypeCode = ls.get(1).toString();
            String dicCode = ls.get(2).toString();
            String dicDesc = "";
            String resume = "";
            String dicGroup = "";
            try {
                dicDesc = ls.get(3).toString();
                //resume = ls.get(4).toString();
                //dicGroup = ls.get(5).toString();
            } catch (Exception e) {
                log.error("导入值域字典时出错：第" + i + "行，" + e);
            }
            if ("DICTYPE".equals(sdTypeCode)) {
                indNo = 0;
                // 获取表单项目id
                SdsQcformItemEntity itemEntity = new SdsQcformItemEntity();
                itemEntity.setEntityId(entityId);
                itemEntity.setBtCode(dicCode);
                itemEntity.setBtIsActive(1);
                itemEntity = this.baseMapper.selectOne(itemEntity);
                if (CommonUtil.isEmpty(itemEntity)) {
                    formItemCode = "";
                    formItemId = null;
                    continue;
                }
                formItemId = itemEntity.getId();
                formItemCode = itemEntity.getBtCode();

                // 如果当前项目值域字典还没有批量无效,先批量无效
                Wrapper<SdsQcfitemDicEntity> dicWpr = new EntityWrapper<>();
                dicWpr.eq("form_item_id", formItemId);
                sdsQcfitemDicMapper.updateForSet("is_active=0", dicWpr);
                continue;
            } else {
                if (formItemId == null) {
                    continue;
                }
                indNo++;
                // 判断值域字典是否重复
                SdsQcfitemDicEntity dicEntity = new SdsQcfitemDicEntity();
                dicEntity.setFormItemId(formItemId);
                dicEntity.setCode(dicCode);
                dicEntity = sdsQcfitemDicMapper.selectOne(dicEntity);
                if (dicEntity == null) {
                    dicEntity = new SdsQcfitemDicEntity();
                    dicEntity.setFormItemId(formItemId);
                    dicEntity.setCode(dicCode);
                    dicEntity.setDesc(dicDesc);
                    //dicEntity.setGroup(dicGroup);
                    dicEntity.setIndNo(indNo);
                    //dicEntity.setResume(resume);
                    dicEntity.setIsActive(1);
                    dicEntity.setUpdateDate(nowDate);

                    dicEntity.insert();
                } else {
                    dicEntity.setDesc(dicDesc);
                    //dicEntity.setGroup(dicGroup);
                    dicEntity.setIndNo(indNo);
                    //dicEntity.setResume(resume);
                    dicEntity.setIsActive(1);
                    dicEntity.setUpdateDate(nowDate);

                    dicEntity.updateAllColumnById();
                }
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importRule(Long entityId, List<List<Object>> all) {
        // 导入前先把当前当前病种的所有检验规则删除
        Wrapper<SdsQcformItemEntity> itemWpr = new EntityWrapper<>();
        itemWpr.eq("entity_id", entityId);
        List<SdsQcformItemEntity> formItems = this.baseMapper.selectList(itemWpr);
        for (SdsQcformItemEntity formItem : formItems) {
            Wrapper<SdsQcfitemMatchRuleEntity> wpr = new EntityWrapper<>();
            wpr.eq("form_item_id", formItem.getId());
            this.sdsQcfitemMatchRuleMapper.delete(wpr);
        }
        for (int i = 1; i < all.size(); i++) {
            List<Object> ls = all.get(i);
            String verCode = ls.get(0).toString();
            String formItemCode = ls.get(1).toString();
            String tipsText = ls.get(2).toString();
            String expMethodCode = ls.get(3).toString();
            Long expMethodId = null;
            if (CommonUtil.isNotEmpty(expMethodCode)) {
                SdsExpressEntity exp = sdsCommonService.getExpEntity("ValiRule", expMethodCode);
                if (CommonUtil.isNotEmpty(exp)) {
                    expMethodId = exp.getId();
                }
            }
            String expStr = "";
            String levelCode = "error";
            try {
                expStr = ls.get(4).toString();
                levelCode = ls.get(5).toString();
            } catch (Exception e) {
                log.error("导入检验规则时出错：第" + i + "行，" + e);
            }
            if (expStr.contains("包含")) {
                if (expStr.contains("不")) {
                    expStr = expStr.replace("不包含", ".contains(");
                    expStr = "!" + expStr + ")";
                } else {
                    expStr = expStr.replace("包含", ".contains(");
                    expStr = expStr + ")";
                }
            }
            // 解决m语法问题，将判等单=替换成==
            if (expStr.contains("this=\"")) {
                expStr = expStr.replace("this=\"", "this==\"");
            }
            if (expStr.contains("this'=\"")) {
                expStr = expStr.replace("this'=\"", "this!=\"");
            }

            Long levelId = null;
            if (CommonUtil.isNotEmpty(levelCode)) {
                levelId = sdsCommonService.getDictId("ControlLevel", captureName(levelCode));
            }

            // 获取表单项目id
            SdsQcformItemEntity itemEntity = new SdsQcformItemEntity();
            itemEntity.setEntityId(entityId);
            itemEntity.setBtCode(formItemCode);
            itemEntity.setBtIsActive(1);
            itemEntity = this.baseMapper.selectOne(itemEntity);
            if (CommonUtil.isEmpty(itemEntity)) {
                continue;
            }
            Long formItemId = itemEntity.getId();
            // 判断检验规则是否重复
            SdsQcfitemMatchRuleEntity matchRuleEntity = new SdsQcfitemMatchRuleEntity();
            matchRuleEntity.setFormItemId(formItemId);
            matchRuleEntity.setControlExpId(expMethodId);
            matchRuleEntity.setControlExp(expStr);
            matchRuleEntity = sdsQcfitemMatchRuleMapper.selectOne(matchRuleEntity);
            if (matchRuleEntity == null) {
                matchRuleEntity = new SdsQcfitemMatchRuleEntity();
                matchRuleEntity.setFormItemId(formItemId);
                matchRuleEntity.setControlExpId(expMethodId);
                matchRuleEntity.setControlExp(expStr);
                matchRuleEntity.setControlLevel(levelId);
                matchRuleEntity.setTipText(tipsText);

                matchRuleEntity.insert();
            } else {
                matchRuleEntity.setControlExp(expStr);
                matchRuleEntity.setControlLevel(levelId);
                matchRuleEntity.setTipText(tipsText);

                matchRuleEntity.updateAllColumnById();
            }
        }
    }

    @Override
    public List<ZTreeNode> getItemTree(Long entityId) {
        Map params = new HashMap();
        params.put("entityId", entityId);
        List<ZTreeNode> tree = new ArrayList<>();
        //1.根据entityId查询病种对应的项目大类
        List<SdsQcformItemEntity> sdsQcformItemEntities = this.baseMapper.selectItemCat(entityId);
        for (SdsQcformItemEntity sdsQcformItemEntity : sdsQcformItemEntities) {
            ZTreeNode zTreeNode = new ZTreeNode();
            long id = IdWorker.getId();
            zTreeNode.setId(id);
            zTreeNode.setpId(0l);
            zTreeNode.setName(sdsQcformItemEntity.getBtItemCat());
            zTreeNode.setIsOpen(true);
            zTreeNode.setIsParent(true);
            tree.add(zTreeNode);
            //2.根据项目大类查询每个项目
            List<SdsQcformItemEntity> itemEntities = this.baseMapper.selectItemByCat(entityId, sdsQcformItemEntity.getBtItemCat());
            for (SdsQcformItemEntity sdsQcformItemEntity1 : itemEntities) {
                ZTreeNode zTreeNode1 = new ZTreeNode();
                zTreeNode1.setId(sdsQcformItemEntity1.getId());
                zTreeNode1.setpId(id);
                zTreeNode1.setName(sdsQcformItemEntity1.getBtDesc());
                zTreeNode1.setIsOpen(false);
                zTreeNode1.setIsParent(false);
                tree.add(zTreeNode1);
            }
        }
        return tree;
    }

    @Override
    public int syncDataConfig(Long entityId) {
        int count = 0;
        // 获取该病种中通用项目
        Wrapper<SdsQcformItemEntity> wpr = new EntityWrapper<>();
        wpr.eq("entity_id", entityId).andNew().like("bt_code", "CM-").or().in("bt_code", "caseId,IDCard");
        List<SdsQcformItemEntity> comItemList = this.baseMapper.selectList(wpr);
        item:for (SdsQcformItemEntity itemEntity : comItemList) {
            String itemCode = itemEntity.getBtCode();
            Long itemId = itemEntity.getId();

            // 获取其他病种的通用数据源配置
            List<Map<String, Object>> configList = this.baseMapper.getConfigByCode(itemCode);
            if (configList.size() == 0) continue;
            boolean upDateFlag = false;
            for (int i = 0; i < configList.size(); i++) {
                Map<String, Object> configMap = configList.get(i);
                Long dsId = null;
                Long linkStandId = null;
                Integer isCache = 0;
                Long getTiming = null;
                String valueItemCode = null;
                if (CommonUtil.isNotEmpty(configMap.get("ds_id"))) {
                    dsId = Long.valueOf(configMap.get("ds_id").toString());
                }
                if (CommonUtil.isNotEmpty(configMap.get("link_stand_id"))) {
                    linkStandId = Long.valueOf(configMap.get("link_stand_id").toString());
                }
                if (CommonUtil.isNotEmpty(configMap.get("get_timing"))) {
                    getTiming = Long.valueOf(configMap.get("get_timing").toString());
                }
                if (CommonUtil.isNotEmpty(configMap.get("bt_is_cache"))) {
                    isCache = Integer.valueOf(configMap.get("bt_is_cache").toString());
                }
                if (CommonUtil.isNotEmpty(configMap.get("value_item_code"))) {
                    valueItemCode = configMap.get("value_item_code").toString();
                }

                // 判断是否已有数据源配置
                SdsDataConfigEntity dataConfigEntity = new SdsDataConfigEntity();
                Wrapper<SdsDataConfigEntity> confWpr = new EntityWrapper<>();
                confWpr.eq("fitem_id", itemId);
                confWpr.isNull("fitem_dic_id");
                dataConfigEntity = dataConfigEntity.selectOne(confWpr);
                if (dataConfigEntity != null) {
                    // 如果是自身或者与之前同步数据没有改变
                    if ((dataConfigEntity.getFitemId().equals(Long.valueOf(configMap.get("fitem_id").toString())))) {
                        continue item;
                    } else {
                        // 先删除全部配置
                        if (i == 0) {
                            dataConfigEntity.delete(confWpr);
                        }
                    }
                }
                dataConfigEntity = new SdsDataConfigEntity();
                dataConfigEntity.setFitemId(itemId);
                dataConfigEntity.setDsId(dsId);
                dataConfigEntity.setLinkStandId(linkStandId);
                dataConfigEntity.setGetTiming(getTiming);
                dataConfigEntity.setBtIsCache(isCache);
                dataConfigEntity.setValueItemCode(valueItemCode);
                dataConfigEntity.setUpdateDate((Date) configMap.get("update_date"));
                dataConfigEntity.setUpdateUser("batch");
                dataConfigEntity.insert();
                upDateFlag = true;
            }
            if (upDateFlag) {
                count++;
            }
        }
        return count;
    }

    @Override
    public int syncItemDefault(Long entityId) {
        int count = 0;
        // 获取该病种中通用项目
        Wrapper<SdsQcformItemEntity> wpr = new EntityWrapper<>();
        wpr.eq("entity_id", entityId).andNew().like("bt_code", "CM-5");
        List<SdsQcformItemEntity> comItemList = this.baseMapper.selectList(wpr);
        for (SdsQcformItemEntity itemEntity : comItemList) {
            Long itemId = itemEntity.getId();
            String itemCode = itemEntity.getBtCode();
            List<SdsQcfitemDicEntity> itemDicList = sdsQcfitemDicMapper.listByItemId(itemId);
            boolean updateFlag = false;
            for (SdsQcfitemDicEntity itemDic : itemDicList) {
                // 获取最新的项目更新
                List<Map<String, Object>> dicItemList = this.baseMapper.getItemDicByCode(itemCode, itemDic.getCode());
                if (dicItemList.isEmpty()) continue;
                Map<String, Object> dicItemMap = dicItemList.get(0);
                Long dicId = (Long) dicItemMap.get("dicId");
                Integer isDefault = (boolean) dicItemMap.get("isDefault") ? 1 : 0;
                if (itemDic.getId() != dicId && itemDic.getIsDefault() != isDefault) {
                    itemDic.setIsDefault(isDefault);
                    itemDic.setUpdateUser("batch");
                    itemDic.setUpdateDate((Date) dicItemMap.get("updateDate"));
                    itemDic.updateAllColumnById();
                    updateFlag = true;
                }
            }
            if (updateFlag) {
                count++;
            }
        }
        return count;
    }

    /**
     * 首字母大写
     */
    public static String captureName(String name) {
        char[] cs = name.toCharArray();
        cs[0] -= 32;
        return String.valueOf(cs);
    }

    /**
     * 转换特殊字符，将json串转换为JS能直接识别的json
     *
     * @param oldJson
     * @retur
     */
    public static String getJsonForJS(String oldJson) {

        String newJson = oldJson;
        newJson = newJson.replaceAll("\\'", "&#39;");
        return newJson;
    }
}